package com.phonemap;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.phonemap.common.Util;
import com.phonemap.models.User;

@SuppressWarnings("serial")
public class UserServlet extends BaseServlet {
	private static final Logger logger = Logger.getLogger(UserServlet.class
			.getCanonicalName());

	/**
	 * Get the requested customer entities in JSON format
	 */
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
//		InitEntity.initDatabase();
//		InitEntity.insertUsers();
		super.doGet(req, resp);
		logger.log(Level.INFO, "Obtaining User listing");
		String searchFor = req.getParameter("q");
		PrintWriter out = resp.getWriter();
		Iterable<Entity> entities = null;
		if (searchFor == null || searchFor.equals("")) {
			entities = User.getAllUsers();
			out.println(Util.writeJSON(entities));
		} else {
			Entity e =  User.getUser(searchFor);
			  if (e != null) {
				Set<Entity> result = new HashSet<Entity>();
				result.add(e);
				out.println(Util.writeJSON(result));
			  }
		}
		return;
	}

	/**
	 * Insert the new customer
	 */
	protected void doPut(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		logger.log(Level.INFO, "Creating User");
		
		String phone = req.getParameter("phone");
		String firstname = req.getParameter("firstname");
		String lastname = req.getParameter("lastname");
		String email = req.getParameter("email");
		String password = req.getParameter("password");
		String avatar = req.getParameter("avatar");
		User.createOrUpdateUser(phone, firstname, lastname, email, password,
				avatar);
	}
	
	/**
	 * Update the user
	 */
	protected void doUpdate(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		logger.log(Level.INFO, "Creating User");
		
		String phone = req.getParameter("phone");
		String firstname = req.getParameter("firstname");
		String lastname = req.getParameter("lastname");
		String workAndEducation = req.getParameter("workAndEducation");
		String live = req.getParameter("live");
		String birthday = req.getParameter("birthdate") != null ? req.getParameter("birthdate") + "/" + req.getParameter("birthyear") : null; 
		String interestedIn = req.getParameter("interestedIn");
		String relationshipStatus = req.getParameter("relationshipStatus");
		String mobilePhone = req.getParameter("mobilePhone");
		String website = req.getParameter("website");
		String introduction = req.getParameter("introduction");
		String email = req.getParameter("email");
		User.updateUser(phone, firstname, lastname, workAndEducation, live, 
				birthday, interestedIn, relationshipStatus, 
				email, mobilePhone, website, introduction);
	}

	/**
	 * Delete the customer
	 */
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String phone = req.getParameter("id");
		logger.log(Level.INFO, "Deleting User {0}", phone);
		Key key = KeyFactory.createKey("User", phone);
		try {
			// CASCADE_ON_DELETE
			Iterable<Entity> entities = Util.listChildKeys("Position", key);
			final List<Key> positionkeys = new ArrayList<Key>();
			for (Entity e : entities) {
				positionkeys.add(e.getKey());

			}
			Util.deleteEntity(positionkeys);
			Util.deleteFromCache(key);
			Util.deleteEntity(key);
		} catch (Exception e) {
			String msg = Util.getErrorResponse(e);
			resp.getWriter().print(msg);
		}
	}

	/**
	 * Redirect the call to doDelete or doPut method
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String action = req.getParameter("action");
		if (action.equalsIgnoreCase("delete")) {
			doDelete(req, resp);
			return;
		} else if (action.equalsIgnoreCase("put")) {
			doPut(req, resp);
			return;
		} else if (action.equalsIgnoreCase("update")) {
			doUpdate(req, resp);
			return;
		}
	}

}
